/*
 * @Author: xiaosihan
 * @Date: 2024-01-10 10:43:35
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-01-10 16:48:30
 */

// 全部图库的公共状态
import { observable, configure } from 'mobx';
// import stickerService from "@/service/stickerService";
import { get } from 'lodash';
import { StickerData, StickerGroup } from '#/type';
import stickerService from '@/api/services/stickerService';

configure({ enforceActions: 'never' });

export interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

// 全部图库管理状态
const stickerStore = observable({
  //全部组
  cascaderOptions: [] as Array<Option>,

  async getStickerGroup() {
    const result = (await stickerService
      .get_sticker_group()
      .catch(() => [])) as Array<StickerGroup>;

    const cascaderOptions: Array<Option> = result.map((g) => {
      return {
        value: g.id,
        label: g.name,
        children: (g.sonList || []).map((g) => {
          return {
            value: g.id,
            label: g.name,
          };
        }),
      };
    });
    this.cascaderOptions = cascaderOptions;
    this.setActiveid([
      get(cascaderOptions, [0, 'value']) as number,
      get(cascaderOptions, [0, 'children', 0, 'value']) as number,
    ]);
  },

  // 当前选中的分组
  activeid: [0, 0],
  setActiveid(activeid: [number, number]) {
    this.activeid = activeid;
    this.page = 1;
    this.stickers = [];
    this.getSticker();
  },

  //加载中
  loading: false,
  setLoading(loading: boolean) {
    this.loading = loading;
  },

  page: 1,
  getNextPage() {
    this.page += 1;
    this.getSticker();
  },
  pageSize: 14,
  hasNext: true,
  // 搜索词
  searchValue: '',
  setSearchValue(searchValue: string) {
    this.page = 1;
    this.stickers = [];
    this.searchValue = searchValue;
    this.getSticker();
  },
  // 图库列表
  stickers: [] as Array<StickerData>,
  async getSticker() {
    this.setLoading(true);
    const { page, pageSize, searchValue, activeid } = this;
    const { list, totalCount } = await stickerService
      .get_sticker({ groupId: activeid[1], pageNo: page, pageSize, searchValue })
      .catch(() => []);
    this.stickers.push(...list);
    this.hasNext = list.length === this.pageSize;
    this.setLoading(false);
  },
});

// 初始获取图库组
stickerStore.getStickerGroup();

export default stickerStore;
